<template>
  <div class="test-credentials">
    <h1>凭据API测试页面</h1>
    
    <div class="test-section">
      <h2>Token状态</h2>
      <p>Token: {{ token || '未找到' }}</p>
      <button @click="checkToken">检查Token</button>
    </div>

    <div class="test-section">
      <h2>API测试</h2>
      <button @click="testGetCredentials">测试获取凭据列表</button>
      <button @click="testCreateCredential">测试创建凭据</button>
    </div>

    <div class="test-section">
      <h2>响应结果</h2>
      <pre>{{ JSON.stringify(apiResponse, null, 2) }}</pre>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ansibleAPI } from '@/api/ansible'

const token = ref('')
const apiResponse = ref(null)

const checkToken = () => {
  token.value = localStorage.getItem('token') || ''
  console.log('当前Token:', token.value)
}

const testGetCredentials = async () => {
  try {
    console.log('开始测试获取凭据列表...')
    const response = await ansibleAPI.getCredentials()
    apiResponse.value = {
      status: 'success',
      data: response.data,
      headers: response.headers
    }
    console.log('获取凭据列表成功:', response.data)
  } catch (error) {
    console.error('获取凭据列表失败:', error)
    apiResponse.value = {
      status: 'error',
      error: error.message,
      response: error.response?.data
    }
  }
}

const testCreateCredential = async () => {
  try {
    console.log('开始测试创建凭据...')
    const testData = {
      name: '测试凭据_' + Date.now(),
      description: '这是一个测试凭据',
      credential_type: 'password',
      username: 'testuser',
      password: 'testpass123',
      is_active: true
    }
    
    const response = await ansibleAPI.createCredential(testData)
    apiResponse.value = {
      status: 'success',
      data: response.data,
      headers: response.headers
    }
    console.log('创建凭据成功:', response.data)
  } catch (error) {
    console.error('创建凭据失败:', error)
    apiResponse.value = {
      status: 'error',
      error: error.message,
      response: error.response?.data
    }
  }
}

onMounted(() => {
  checkToken()
})
</script>

<style scoped>
.test-credentials {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.test-section {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 8px;
}

button {
  margin: 5px;
  padding: 10px 15px;
  background: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:hover {
  background: #0056b3;
}

pre {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 4px;
  overflow-x: auto;
  max-height: 400px;
}
</style>
